package org.sibframework.sda.services;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ModelNameService {

	public static final String Model_Names_File = "model_names.properties";
	
	private static ModelNameService INSTANCE = null;
	
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	private Map<String, Class<?>> cache = new HashMap<String, Class<?>>();

	public ModelNameService() {

		//search configure file in install dir first.
		try {

			File configFile = new File(Model_Names_File);
			if (configFile.exists() && configFile.isFile()) {
				this.init(new FileInputStream(configFile));
				logger.info("Load model names from install directory.");
				return;
			}
		} catch (FileNotFoundException e) {
		}
		
		//search configure file in class path then.
		InputStream is = this.getClass().getClassLoader().getResourceAsStream(Model_Names_File);
		this.init(is);
		logger.info("Load model names from classpath.");
	}
	
	
	/**
	 * initial this factory use a give configuration file stream.
	 * @param is
	 */
	public void init(InputStream is) {
		try {

			//load from properties files
	        Properties prop = new Properties();
	        prop.load(is);
	        
	        for (Object key :prop.keySet()) {
	        	try {
					Class<?> clazz = Class.forName((String) prop.get(key));
					cache.put((String) key, clazz);
				} catch (Exception e) {
					e.printStackTrace();
				}
	        }
	        
			is.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
	
	public Class<?> getModelClass(String modelName) {
		return cache.get(modelName);
	}


	public static ModelNameService getINSTANCE() {
		if (INSTANCE == null) {
			INSTANCE = new ModelNameService();
		}
		return INSTANCE;
	}


	public static void setINSTANCE(ModelNameService iNSTANCE) {
		INSTANCE = iNSTANCE;
	}
	
	
}
